package com.icss.train_sys_back.mapper.home;

import com.icss.train_sys_back.entity.home.CreateOrderDTO;
import com.icss.train_sys_back.entity.home.OrderEntity;
import com.icss.train_sys_back.entity.home.OrderPassengerDTO;
import com.icss.train_sys_back.entity.home.OrderPassengerEntity;
import com.icss.train_sys_back.entity.ticket_manage.TicketEntity;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.annotations.Param;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * @Author 小泽
 * @createTime 2025/10/13 10:35
 */
@Mapper
public interface OrderMapper {
    //插入订单信息
    @Insert("insert into t_order values (#{orderId},#{userId},#{ticketId},#{orderPrice},#{orderStatus},null,now(),null)")
    boolean addOrder(OrderEntity order);

    //查询是否还有可用座位
    @Select("select seat_id from t_ticket ti " +
            "left join t_train_number tn on ti.train_number_id=tn.id " +
            "left join t_seat se on tn.train_number=se.train_number " +
            "where ti.ticket_id =  #{ticketId} and ti.carriage_type= se.seat_type" +
            " and se.status = 0 limit #{size}")
    List<Integer> querySeat(String ticketId, Integer size);

    //有可用座位，则对其状态进行修改
    @Update("<script>" +
            "update t_seat set status=2 where seat_id in " +
            "<foreach collection='list' item='sid' index='index' open='(' close=')' separator=','>#{sid}</foreach>" +
            "</script>")
    void updateSeatStatus(List<Integer> hasSeat);

    //向订单--乘车人表插入信息
    @Insert("<script>" +
            "INSERT INTO t_order_passenger (order_id, passenger_id, seat_id) VALUES " +
            "<foreach collection='list' item='item' separator=','>" +
            "   (#{item.orderId}, #{item.passengerId}, #{item.seatId})" +
            "</foreach>" +
            "</script>")
    void batchInsertOrderPassenger(@Param("list") List<OrderPassengerDTO> list);

    //根据订单编号查询相关信息
    @Select("select * from t_order o left join t_ticket t on o.ticket_id=t.ticket_id where order_id=#{orderId} ")
    @Results({
            @Result(property = "orderId", column = "order_id"),
            @Result(property = "ticket.trainNumberId", column = "train_number_id"),
            @Result(property = "ticket.carriageType", column = "carriage_type"),
            @Result(property = "ticket.startStationId", column = "start_station_id"),
            @Result(property = "ticket.arrivalStationId", column = "arrival_station_id"),
            @Result(property = "ticket.departureTime", column = "departure_time"),
            @Result(property = "ticket.arrivalTime", column = "arrival_time"),
            @Result(property = "ticket.ticketPrice", column = "ticket_price"),
            @Result(property = "orderPassengerDTOList", column = "order_id",
                    javaType = List.class,
                    many = @Many(select = "com.icss.train_sys_back.mapper.home.OrderMapper.selectByOrderId"))
    })
    OrderEntity getOrderInfo(String orderId);

    @Select("select * from t_order_passenger top left join t_passenger tp on top.passenger_id=tp.passenger_id left join t_seat ts on top.seat_id=ts.seat_id where top.order_id=#{orderId}")
    List<OrderPassengerDTO> selectByOrderId(String orderId);

    @Update("update t_order set order_status=1,pay_time=now() where order_id= #{outTradeNo}")
    int updateOrderStatus2(String outTradeNo);

    //根据订单号查到order_passenger里的数据
    @Select("select * from t_order_passenger where order_id = #{orderId}")
    List<OrderPassengerEntity> findOrderPassengerListByOrderId(String orderId);

    //根据seat_id查seat表 ，获取到座位号对应的车辆号和车厢号
    @Select("select train_number,carriage_number from t_seat where seat_id = #{seatId}")
    Map<String, Object> findTrainAndCarriageBySeatId(Integer seatId);

    //根据车辆号 和 车厢号 ，将train_carriage 表中   车厢号的座位数量+1
    @Update("update t_train_carriage set seat_count = seat_count+1 where carriage_number = #{carriageNumber} and train_number = #{trainNumber}")
    int updateCarriageSeatCountByCarriageAndTrainNumber(Integer carriageNumber, String trainNumber);

    //删除order_passenger表的数据
    @Delete("delete from t_order_passenger  where order_id = #{orderId}")
    void deleteOrderPassengerRecordsByOrderId(String orderId);

    //更新order表状态为已取消
    //'订单状态：0-待支付，1-已支付，2-已取消  3-退票'
    @Update("update t_order set order_status = #{status} where order_id = #{orderId}")
    void updateOrderStatus(String orderId, Integer status);

    //座位状态恢复为0
    @Update("<script>" +
            "update t_seat set status = 0 where seat_id in " +
            "<foreach collection='list' item='sid' index='index' open='(' close=')' separator=','>#{sid}</foreach>" +
            "</script>")
    void updateSeatStatusCancel(List<Integer> seatIds);

    //验证是否重复购票 -- 查order_passenger表是否有该 passengerIds里的记录
    List<OrderPassengerEntity> checkIsRepeatBuyTicket(CreateOrderDTO createOrder);

    @Select("select * from t_passenger_user pu " +
            "left join t_order_passenger op on pu.t_passenger_id  = op.passenger_id " +
            "where pu.t_user_id  = #{userId} " +
            "and op.order_id = #{orderId}")
    OrderPassengerEntity queryByUserId(Integer userId, String orderId);

    @Update("update t_seat set status = #{status}  where seat_id = #{seatId}")
    void updateSeatStatusById(Integer seatId, int status);

    //根据车票Id 关联order_passenger表 找到对应的 seatId
    @Select("select ts.seat_id from t_order o " +
            "left join t_order_passenger op on o.order_id = op.order_id" +
            " left join t_seat ts on op.seat_id = ts.seat_id " +
            " where o.ticket_id = #{ticketId} and op.passenger_id = #{passengerId}  ")
    Integer findSeatIdByTicketId(String ticketId, Integer passengerId);

    //改签车次查询  startStationId = 3，endStationId = 15，date = 2025-11-19，timeRange = 06:00-12:00
    List<TicketEntity> getNewTrainTickets(Integer startStationId, Integer endStationId, LocalDate dateTime);

}
